/*
 * MainView.java
 */

package org.robcash.apps.messagepopup.view;

import static org.robcash.apps.messagepopup.BeanNameConstants.SUBSCRIPTION_BEAN_NAME;

import org.robcash.apps.messagepopup.Main;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.robcash.apps.messagepopup.action.SaveSubscriptionStoreTask;
import org.robcash.apps.messagepopup.model.Model;
import org.robcash.apps.messagepopup.view.components.SubscriptionTableModel;
import org.robcash.apps.messagepopup.view.wizard.SubscriptionModel;
import org.robcash.apps.messagepopup.vo.Subscription;
import org.robcash.apps.messagepopup.vo.SubscriptionStore;
import org.robcash.commons.swing.wizard.Wizard;
import org.robcash.commons.swing.wizard.impl.WizardDialog;
import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor;

/**
 * The application's main frame.
 */
public class MainView extends FrameView implements TableModelListener {

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private boolean changesPending = false;

    public MainView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    public boolean isChangesPending() {
        return changesPending;
    }

    public void setChangesPending(boolean b) {
        boolean old = isChangesPending();
        this.changesPending = b;
        firePropertyChange("changesPending", old, isChangesPending());
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Main.getApplication().getMainFrame();
            aboutBox = new MainAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Main.getApplication().show(aboutBox);
    }

    @Action
    public void addSubscription() {
        // To add a subscription, we must launch the subscription wizard
        JFrame mainFrame = Main.getApplication().getMainFrame();
        SubscriptionStore store = Model.getInstance().getSubscriptionStore();
        SubscriptionModel model = new SubscriptionModel();
        model.setSubscriptionStore(store);
        Wizard wizard = new WizardDialog(mainFrame, model);
        wizard.setTitle("Add a Subscription");
        wizard.getDialog().setLocationRelativeTo(mainFrame);
        int returnCode = wizard.showDialog();
        if ( returnCode == Wizard.STATUS_FINISH ) {
            GenericBeanFactoryAccessor beanFactory = Main.getApplication().getSpringContext();
            Subscription subscription = beanFactory.getBean(SUBSCRIPTION_BEAN_NAME);
            subscription.setName(model.getSubscriptionName());
            subscription.setMessageStore(model.getMessageStore());
            subscription.setSchedule(model.getSchedule());
            store.add(subscription);
            setChangesPending(true);
        }
    }

    @Action(enabledProperty = "changesPending")
    public Task saveSubscriptionStore() {
        return new SaveSubscriptionStoreTask(getApplication());
    }

    @Action
    public void manageSchedules() {
        ScheduleManagerDialog scheduleManager = new ScheduleManagerDialog(this.getFrame());
        scheduleManager.setSubscriptionStore(Model.getInstance().getSubscriptionStore());
        scheduleManager.setLocationRelativeTo(this.getFrame());
        scheduleManager.setVisible(true);
        if ( scheduleManager.getReturnStatus() == ScheduleManagerDialog.RET_OK ) {
            setChangesPending(true);
        }
    }

    public void tableChanged(TableModelEvent e) {
        if ( e.getSource().equals(subscriptionTable.getModel()) ) {
            setChangesPending(true);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        saveMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        toolsMenu = new javax.swing.JMenu();
        scheduleManagerMenuItem = new javax.swing.JMenuItem();
        addSubscriptionMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        toolBar = new javax.swing.JToolBar();
        manageSchedulesButton = new javax.swing.JButton();
        addWebSubButton = new javax.swing.JButton();
        subscriptionTableScrollPane = new javax.swing.JScrollPane();
        subscriptionTable = new org.robcash.apps.messagepopup.view.components.SubscriptionTable();

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.robcash.apps.messagepopup.Main.class).getContext().getResourceMap(MainView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.robcash.apps.messagepopup.Main.class).getContext().getActionMap(MainView.class, this);
        saveMenuItem.setAction(actionMap.get("saveSubscriptionStore")); // NOI18N
        saveMenuItem.setText(resourceMap.getString("saveMenuItem.text")); // NOI18N
        saveMenuItem.setToolTipText(resourceMap.getString("saveMenuItem.toolTipText")); // NOI18N
        saveMenuItem.setName("saveMenuItem"); // NOI18N
        fileMenu.add(saveMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        toolsMenu.setText(resourceMap.getString("toolsMenu.text")); // NOI18N
        toolsMenu.setName("toolsMenu"); // NOI18N

        scheduleManagerMenuItem.setAction(actionMap.get("manageSchedules")); // NOI18N
        scheduleManagerMenuItem.setName("scheduleManagerMenuItem"); // NOI18N
        toolsMenu.add(scheduleManagerMenuItem);

        addSubscriptionMenuItem.setAction(actionMap.get("addSubscription")); // NOI18N
        addSubscriptionMenuItem.setName("addSubscriptionMenuItem"); // NOI18N
        toolsMenu.add(addSubscriptionMenuItem);

        menuBar.add(toolsMenu);

        helpMenu.setAction(actionMap.get("showAboutBox")); // NOI18N
        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 250, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        toolBar.setRollover(true);
        toolBar.setName("toolBar"); // NOI18N

        manageSchedulesButton.setAction(actionMap.get("manageSchedules")); // NOI18N
        manageSchedulesButton.setFocusable(false);
        manageSchedulesButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        manageSchedulesButton.setName("manageSchedulesButton"); // NOI18N
        manageSchedulesButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolBar.add(manageSchedulesButton);

        addWebSubButton.setAction(actionMap.get("addSubscription")); // NOI18N
        addWebSubButton.setFocusable(false);
        addWebSubButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addWebSubButton.setName("addWebSubButton"); // NOI18N
        addWebSubButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolBar.add(addWebSubButton);

        subscriptionTableScrollPane.setName("subscriptionTableScrollPane"); // NOI18N

        subscriptionTable.setName("subscriptionTable"); // NOI18N
        ((SubscriptionTableModel) subscriptionTable.getModel()).addAll(Model.getInstance().getSubscriptionStore().getSubscriptions());
        subscriptionTableScrollPane.setViewportView(subscriptionTable);

        subscriptionTable.getModel().addTableModelListener(this);

        setComponent(subscriptionTableScrollPane);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
        setToolBar(toolBar);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem addSubscriptionMenuItem;
    private javax.swing.JButton addWebSubButton;
    private javax.swing.JButton manageSchedulesButton;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem saveMenuItem;
    private javax.swing.JMenuItem scheduleManagerMenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private org.robcash.apps.messagepopup.view.components.SubscriptionTable subscriptionTable;
    private javax.swing.JScrollPane subscriptionTableScrollPane;
    private javax.swing.JToolBar toolBar;
    private javax.swing.JMenu toolsMenu;
    // End of variables declaration//GEN-END:variables

}
